package com.noahplat.person.service.impl;

import com.alibaba.druid.support.spring.stat.annotation.Stat;
import com.noahplat.common.utils.Result;
import com.noahplat.common.utils.StatusCode;
import com.noahplat.person.mapper.HealthRecordMapper;
import com.noahplat.person.mapper.PhysicalMapper;
import com.noahplat.person.pojo.HealthRecord;
import com.noahplat.person.pojo.Physical;
import com.noahplat.person.service.PhysicalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @ClassName: PhysicalServiceImpl
 * @Description: 体检记录实现类
 * @Author 李景星
 * @Date 2021/3/8
 * @Version 1.0
 */
@Service
public class PhysicalServiceImpl implements PhysicalService {

    @Autowired
    private PhysicalMapper physicalMapper;
    @Autowired
    private HealthRecordMapper healthRecordMapper;

    /**
     * 获取体检记录
     * @param pid
     * @return
     */
    @Override
    public Result getPhysical(Long pid) {
        //获取体检记录
        Example physicalExample = new Example(Physical.class);
        physicalExample.createCriteria().andEqualTo("pid", pid);
        Physical physical = physicalMapper.selectOneByExample(physicalExample);
        //获取体检报告
        Example healthRecordExample = new Example(HealthRecord.class);
        healthRecordExample.createCriteria().andEqualTo("pid", pid).andEqualTo("del", "N");
        healthRecordExample.setOrderByClause("id desc");
        List<HealthRecord> healthRecords = healthRecordMapper.selectByExample(healthRecordExample);

        if (ObjectUtils.isEmpty(physical)){
            Physical newPhysical = new Physical(pid, "", "", "", "", "", "", "");
            physicalMapper.insert(newPhysical);
            return new Result(true, StatusCode.OK, "查询成功", newPhysical);
        }
        //封装体检报告
        physical.setHealthRecords(healthRecords);
        return new Result(true, StatusCode.OK, "查询成功", physical);
    }

    /**
     * 更新体检记录
     * @param physical
     * @return
     */
    @Override
    public Result updatePhysical(Physical physical) {
        int res = physicalMapper.updateByPrimaryKeySelective(physical);
        if(res > 0){
            return new Result(true, StatusCode.OK, "更新成功");
        }
        return new Result(false, StatusCode.ERROR, "更新失败");
    }
}
